package com.zkq.graduate.interceptor;

import com.alibaba.fastjson.JSON;
import com.zkq.graduate.enums.DateTimeFormatterEnum;
import com.zkq.graduate.pojo.SystemTime;
import com.zkq.graduate.service.SystemTimeService;
import com.zkq.graduate.util.LocalDateTimeUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @Author zhangkaiqiang
 * @Date 2019/12/27  11:24
 * @Description TODO
 *
 * 时间拦截器,判断当前时间是否在允许的时间范围内
 */
@Component
public class TimeInterceptor implements HandlerInterceptor {


	@Resource(name = "systemTimeService")
	private SystemTimeService systemTimeService;


	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// 如果不是映射方法直接通过
		if(!(handler instanceof HandlerMethod)){
			return true;
		}

		// 请求的url--Spring最佳匹配的url
		String url=request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE).toString();

		// 请求的参数
		HashMap<String,String> params=new HashMap<>(16);
		Map<String,String[]> parameterMap=request.getParameterMap();
		Set<Map.Entry<String,String[]>> entrySet=parameterMap.entrySet();
		for (Map.Entry<String, String[]> entry : entrySet) {
			String key = entry.getKey();
			String value = entry.getValue()[0];
			params.put(key, value);
		}

		// 进行时间范围的判断
		if(operatorLimit(url,params)){
			return true;
		}

		Map<String,Object> resultMap=new HashMap<>(16);
		resultMap.put("code",900);
		resultMap.put("message","当前操作不在允许的时间范围内");
		response.getWriter().print(JSON.toJSONString(resultMap));
		return false;
	}


	/**
	 * 判断是否在允许时间内的方法
	 * @return
	 */
	private boolean operatorLimit(String url, Map<String,String> params){
		if(StringUtils.isNotBlank(url)&&params!=null){
		// 根据请求的url得到是哪个时间限制
			String limitName=getLimitNameByUrl(url,params.get("flag"));
			return testTime(limitName);
		}
		return false;
	}


	/**
	 * 校验当前时间是否在设定时间之间
	 */
	private boolean testTime(String timeName){
		Optional<SystemTime> time=systemTimeService.findByName(timeName);
		return time.map(systemTime -> LocalDateTimeUtil.getBetweenTimeWithString(systemTime.getStartTime(), LocalDateTimeUtil.getStringNow()) >= 0 &&
				LocalDateTimeUtil.getBetweenTimeWithString(systemTime.getEndTime(), LocalDateTimeUtil.getStringNow()) <= 0).orElse(false);
	}


	private String getLimitNameByUrl(String url,String flag){
		String year= LocalDateTimeUtil.formatLocalDateTime(LocalDateTime.now(), DateTimeFormatterEnum.YEAR);
		int classes=Integer.valueOf(year)-4;
		StringBuilder limitName=new StringBuilder(String.valueOf(classes));
		if(StringUtils.isNotBlank(url)){
			switch (url){
				case "/api/v1/student/title/{titleId}":
					limitName.append("级选题时间");
				case "/api/v1/student/openAndPaper":
					if(Objects.equals(flag,"open")){
						limitName.append("级开题报告提交时间");
					} else if(Objects.equals(flag,"paper")){
						limitName.append("级毕业提交论文时间");
					}
					break;
				case "/api/v1/student/design":
					limitName.append("级毕业设计提交时间");
					break;
				default:
					break;
			}
		}
		return limitName.toString();
	}
}
